// 收到1开头的消息
import store from '@/store'
import { resArr } from '../socketOnMessageTools'
import { ifContactInList, decryptMessage } from '../socketTools'
import tools from '../tools'
import { sendSock } from '@/utils/socketSend'

// 解析消息
const decryptMsg = decryptMessage
// 判断缓存的用户列表中是否有该用户
const ifContactInContactlist = ifContactInList

export default async (type, result) => {
  switch (type) {
    // 收到新的好友请求
    case '1.1.1': {
      store.dispatch('addressList/getRequestCount')
      store.dispatch('addressList/getFriendsRequestList')
      break
    }
    // 被好友删除
    case '1.1.2': {
      store.dispatch('addressList/getMyAddressList')
      decryptMsg(result.body, ['id'], '0')
      const userID = resArr[0].id
      // 如果此人之前在好友列表中 则将其身份从好友转化为非好友
      if (store.state.chatInformation.chatInformation.some(item => item.id === userID && item.id_type === 1)) {
        store.commit('chatInformation/reset_identify', {
          id: userID,
          bool: false
        })
      }
      break
    }
    // 成为新好友
    case '1.1.3': {
      store.dispatch('addressList/getRequestCount')
      store.dispatch('addressList/getFriendsRequestList')
      await store.dispatch('addressList/getMyAddressList')
      decryptMsg(result.body, ['id', 'user_img', 'user_name'], 0)
      const userInfo = { ...resArr[0] }
      ifContactInContactlist(userInfo.id, 1)
      // 如果此人之前在聊天列表中 则将其身份从非好友转化为好友
      store.commit('chatInformation/reset_identify', {
        id: userInfo.id,
        bool: true
      })
      store.commit('chatInformation/set_topContact', {
        id_type: 1,
        in_contact: true,
        messages: [],
        time: +new Date(),
        id: userInfo.id,
        name: tools.getContactInfo(userInfo.id, 1).user_name,
        draft: ''
      })
      if (store.state.addressList.recentAgreeId === userInfo.id) {
        sendSock({
          type: '2.2.1',
          body: {
            id: store.state.addressList.recentAgreeId,
            timestamp: +new Date(),
            msg: '我们成为好友了，来跟我聊天吧～'
          }
        })
        store.commit('socket/set_operationReqId', 'sendMessageId')
        const chatInfo = { type: 'words', msg: '我们成为好友了，来跟我聊天吧～', isSelf: true, timestamp: +new Date() }
        store.dispatch('chatInformation/setAddMessage', {
          message: chatInfo,
          id: store.state.addressList.recentAgreeId,
          idType: 1
        })
        store.commit('addressList/set_recentAgreeId', null)
        // 重新获取通讯录列表（防止移动端操作 电脑不更新）
        store.dispatch('addressList/getMyAddressList')
      }
      break
    }
    // 好友请求被拒绝
    case '1.1.4': {
      store.dispatch('addressList/getFriendsRequestList')
      break
    }
  }
}
